//
//  YDComposeViewController.swift
//  YDWeibo01
//
//  Created by suibian on 16/8/17.
//  Copyright © 2016年 iitcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class YDComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        // Do any additional setup after loading the view.
    }
    //    监听事件
    @objc private func cancelAction(){
        //        取消键盘第一响应
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    @objc private func sendAction(){
        print("发布按钮点击")
//        定义一个字符串保存内容 让获取到的模型中的chs描述文字 与填写的字符串拼接
        var allText:String = ""
//        遍历副文本
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (result, range, _) -> Void in
            print(result,range)
            if let attachment = result["NSAttachment"] as? YDTextAttachment{
                print(attachment.emoticonModel?.chs)//获取到了描述文字
//            代表是自定义的文字附件
            allText += attachment.emoticonModel?.chs ?? ""
            }else{
//            是普通字符串
//                截取对应位置的字符串
                let str = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                allText += str
            }
            
        }
        //    发布按钮点击 带有文本附件不能在方法中发布 需要在update和upload方法中添加用自定义文本附件的model中文本附件获取到的字符串 再拼接好的字符串 才能 发布文字微博或者图片微博
        composePictureView.imageList.count == 0 ? update(allText) : upload(allText)
    }

    
// 设置视图
    private func setUpUI(){
    view.backgroundColor = UIColor.whiteColor()
        setUpNav()
//        添加控件
        view.addSubview(composeTextView)
        view.addSubview(bottomView)
        composeTextView.addSubview(composePictureView)
        
//        添加约束
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
            
        bottomView.snp_makeConstraints(closure: { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view).offset(UIEdgeInsetsZero)
                make.height.equalTo(44)
        })
        composePictureView.snp_makeConstraints(closure: { (make) -> Void in
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: KSCREENW - 20, height: KSCREENW - 20))
            make.centerX.equalTo(composeTextView)
        })
        }
//    监听底部按钮点击回调
        bottomView.closure = {[weak self](type:YDComposeBottomViewType)->()in
            switch type{
            case .Toolbar:
                self?.selectImage()
                print("图片")
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case.Emoticon:
                print("笑脸")
                self?.switchKeyBoard()
            case.Add:
                print("+")

            }

        }
//        02选择图片的闭包回调(加号图片点击取得图片)
        composePictureView.closure = {[weak self] in
//            04
            self?.selectImage()
        
        
        }
//        注册通知 监听键盘将要改变frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
//        注册通知 监听删除键盘中的自定义按钮点击 必学写在这 放到其他地方可能注册多次 删除文字出问题
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButtonNofi", name: WEBDELETEBUTTONACTION, object: nil)
//        注册通知 监听20个自定义按钮键盘 点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonNoti:", name: WEBBUTTONACTION, object: nil)
        
    }
//    删除按钮事件
    func emoticonDeleteButtonNofi(){
//        删除文字
        composeTextView.deleteBackward()
    }
//    表情按钮事件
    func emoticonButtonNoti(noti:NSNotification){
//        判断是否为nil 而且是否可以转成emoticonModel
        guard let emoticonModel = noti.object as?YDEmoticonModel else{
            return
        }
//        判断是emoji表情 还是图片表情
        if emoticonModel.isEmoji{
//            十六进制字符串转为字符串
            let str = (emoticonModel.code ?? "" as NSString).emoji()
//              
            composeTextView.insertText(str)
        }else{
//            获取当前已有的副文本
            let allAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            //        图片表情
//        创建不可变副文本(带有文字附件)
            let attr = NSAttributedString.emoticonAttributedString(emoticonModel, textFont: 16, y: -4)
//            获取光标的范围
            let seletRange = composeTextView.selectedRange
//            替换
            allAttr.replaceCharactersInRange(seletRange, withAttributedString: attr)
//            设置allAttr的所有元素的font 从0位置 开始 到最后整个的长度
        allAttr.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16)], range: NSRange(location: 0, length: allAttr.length))
//            添加副文本
            composeTextView.attributedText = allAttr
//            更改光标
            composeTextView.selectedRange = NSRange(location: seletRange.location + 1, length: 0)
//            发送系统通知 隐藏站位文字 (因为是副文本不是原先设置的字符串 所以还需要调用一下系统的通知 让文字隐藏)
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
//            使用系统的代理指定协议方法
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
    }
//     监听键盘将要改变frame
    func keyboardWillChangeFrame(noti:NSNotification){
    print(noti.userInfo)
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
        return
        }
       guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
        return
        
        }
//    获取到cgrect
        let newRect = rect.CGRectValue()
//        跟新约束
        bottomView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(newRect.origin.y - KSCREENH)
        }
//        设置动画
        UIView.animateWithDuration(duration) { () -> Void in
//            强制刷新UI
            self.view.layoutIfNeeded()
        }
    }
    private func setUpNav(){
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发表", style: UIBarButtonItemStyle.Plain, target: self, action: "sendAction")
//        设置不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    
    }
    

//    懒加载控件
    private lazy var titleView:UILabel = {
        //        用户的昵称
        let name = YDUserAccountViewModel.sharedTools.useAccount!.screen_name!
//        显示内容
        let str = "发微博\n\(name)"
//        获取范围
        let range = (str as NSString).rangeOfString(name)
//        初始化一个副文本
        let attr = NSMutableAttributedString(string: str)
//        设置副文本
        attr.addAttributes([NSForegroundColorAttributeName:AppThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
        
        let lab = UILabel()

        lab.attributedText = attr
//        设置约束
        
        lab.textAlignment = .Center
        lab.numberOfLines = 0
//        先设置约束 在设置lab.sizeToFit() 否则会报错
        lab.sizeToFit()
        return lab
    
    }()
    
//    懒加载控件  自定义textView
    private lazy var composeTextView: YDComposeTextView = {
        let textView = YDComposeTextView()
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(16)
        textView.placehodel = "传智播客31期"
//        允许上下移动
        textView.alwaysBounceVertical = true
        return textView
    
    
    }()
    
    //  懒加载控件 自定义bottomview
    private lazy var bottomView:YDComposeBottomView = YDComposeBottomView()
    
//    懒加载配图
    private lazy var composePictureView:YDComposePictureView = YDComposePictureView()
    
//    自定义表情键盘
    private lazy var keyboardView:YDEmotionLeyBoardView = YDEmotionLeyBoardView(frame: CGRect(x: 0, y: 0, width: KSCREENH, height: 216))
//    移除通知
    deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
//    
}

extension YDComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
//        如果有文字才可以点击
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
//        滚动式键盘取消
        self.composeTextView.resignFirstResponder()
    }

}
//  处理bottomViewbutton的点击事件
extension YDComposeViewController{
//          选择图片
    func selectImage(){
        let pickerVc = UIImagePickerController()
//        设置代理
        pickerVc.delegate = self

        self.presentViewController(pickerVc, animated: true, completion: nil)
    }
//          切换接盘
    func switchKeyBoard(){
//        composeTextView.inputView
//        显示的为系统键盘
        if composeTextView.inputView == nil{
            composeTextView.inputView = keyboardView
            bottomView.isEmotion = true
        }else{
            
//        自定义的键盘
        
        composeTextView.inputView = nil
            bottomView.isEmotion = false
            
        }
//        刷新
    composeTextView.reloadInputViews()
        composeTextView.becomeFirstResponder()
    }

}
extension YDComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
//废弃的方法
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
////         设置背景图片 用的是选中的那张图片
//        composeTextView.backgroundColor = UIColor(patternImage: image)
    //        设置背景图片
    //        composeTextView.backgroundColor = UIColor(patternImage: UIImage(named: "compose_emoticonbutton_background_highlighted")!)
////        关闭控制器
//        picker.dismissViewControllerAnimated(true, completion: nil)
//    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        print(info)
//        这个方法要转成uiimage
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
//        let image1 = UIImage.dealImagescale(image, width: 600)
//        let data = UIImagePNGRepresentation(image1)
//        data?.writeToFile("/Users/suibian/Desktop/哈哈.png", atomically: false)
        
//        composeTextView.backgroundColor = UIColor(patternImage: image)
        composePictureView.addImage(UIImage.dealImagescale(image, width: 600))
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
//      压缩图片
    func dealImagescale(image:UIImage,width:CGFloat) ->UIImage{
//    用户上传的图片 要先压缩后上传 服务器那边会保存一张高清的和一张普通的 调用的时候给你
//        等比例压缩
        if image.size.width < width{
        return image
        
        }
        let height = image.size.height * width/image.size.width
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
//        开启上下文
        UIGraphicsBeginImageContext(rect.size)
//    把内容渲染到上下文中
        image.drawInRect(rect)
//        获取上下文中的图片
        let result = UIGraphicsGetImageFromCurrentImageContext()
//        关闭上下文
        UIGraphicsEndImageContext()
        return result
    }
//取消后 想要触发其他事件 就要调用这个方法
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }

}
//发布微博
extension YDComposeViewController{
// 发布文字微博
    func update(status:String){
        YDNetWorkTools.shareTools.composeUpdate(status, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功"
            )
            NSNotificationCenter.defaultCenter().postNotificationName("updataReload", object: nil)
                self.cancelAction()
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
//    发布图片微博
    func upload(status:String){
        YDNetWorkTools.shareTools.composeUpload(status, images: composePictureView.imageList, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功"
            )
            NSNotificationCenter.defaultCenter().postNotificationName("updataReload", object: nil)
                self.cancelAction()
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
        

//            上传多张图片
//            for (i,image) in self.composePictureView.imageList.enumerate(){
//                //            把上传的文件凭借在表单后面
//                let data = UIImagePNGRepresentation(image)!
//                formdata.appendPartWithFileData(data, name: "pic\(i+1)", fileName: "xss", mimeType: "application/octet-stream")
//            }
//            上传一张图片
        
    }
}
